package com.comtop.springboot.templet.modules.sys.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.comtop.springboot.templet.common.exception.CustomException;
import com.comtop.springboot.templet.modules.sys.entity.SysRoleEntity;
import com.comtop.springboot.templet.modules.sys.mapper.SysRoleMapper;
import com.comtop.springboot.templet.modules.sys.service.ISysRoleService;
import com.comtop.springboot.templet.modules.sys.service.ISysUserService;
import com.comtop.springboot.templet.common.utils.Constant;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



/**
 * 角色
 * 
 * @author wangjiafang
 * @version 1.0
 * @since 2016年9月18日 上午9:45:12
 */
@Service("sysRoleService")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper,SysRoleEntity> implements ISysRoleService {
	/**角色mapper**/
	@Autowired
	private SysRoleMapper sysRoleMapper;
	/**角色-菜单关系服务**/
	@Autowired
	private com.comtop.springboot.templet.modules.sys.service.ISysRoleMenuService ISysRoleMenuService;
	/**用户服务**/
	@Autowired
	private ISysUserService ISysUserService;


	@Override
	public Page<SysRoleEntity> queryRoleList(Page<SysRoleEntity> page,Map<String, Object> map) {
		return page.setRecords(sysRoleMapper.queryRoleList(map));
	}

	@Override
	public List<SysRoleEntity> queryRoleList(Map<String, Object> map) {
		return sysRoleMapper.queryRoleList(map);
	}

	@Override
	@Transactional
	public void save(SysRoleEntity role) {
		role.setCreateTime(new Date());
		sysRoleMapper.insert(role);
		
		//检查权限是否越权
		checkPrems(role);
		
		//保存角色与菜单关系
		ISysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
	}

	@Override
	@Transactional
	public void update(SysRoleEntity role) {
		sysRoleMapper.updateById(role);
		
		//检查权限是否越权
		checkPrems(role);
		
		//更新角色与菜单关系
		ISysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
	}

	@Override
	@Transactional
	public void deleteRoleBatch(Long[] roleIds) {
		sysRoleMapper.deleteRoleBatch(roleIds);
	}
	
	@Override
	public List<Long> queryRoleIdList(Long createUserId) {
		return sysRoleMapper.queryRoleIdList(createUserId);
	}

	/**
	 * 检查权限是否越权
	 */
	private void checkPrems(SysRoleEntity role){
		//如果不是超级管理员，则需要判断角色的权限是否超过自己的权限
		if(role.getCreateUserId() == Constant.SUPER_ADMIN){
			return ;
		}
		
		//查询用户所拥有的菜单列表
		List<Long> menuIdList = ISysUserService.queryUserAllMenuId(role.getCreateUserId());
		
		//判断是否越权
		if(!menuIdList.containsAll(role.getMenuIdList())){
			throw new CustomException("新增角色的权限，已超出你的权限范围");
		}
	}
}
